package com.heima.gateway.filter;

import com.alibaba.nacos.common.utils.StringUtils;
import com.heima.utils.common.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
/***
 * 自动生效：Spring Boot 自动扫描并注册到过滤器链
 * 无法动态配置：过滤器行为在代码中写死
 * 适用场景：无需外部配置的固定逻辑（如基础鉴权）
 * */
@Slf4j
@Component
public class TokenGlobalFilter implements GlobalFilter {
    /**
     * token header名称
     */
    private static final String HEADER_TOKEN = "Authorization";
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1. 获取请求响应对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //2. 放行登录请求
        String path = request.getURI().getPath();
        if (StringUtils.contains(path, "/login")) {
            log.info("{}:请求来了",path);
            return chain.filter(exchange);
        }
        //3. 获取请求头中的token
        String token = request.getHeaders().getFirst("token");
        if (StringUtils.isBlank(token)) {
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        //4. 校验token
        Claims claims = AppJwtUtil.getClaimsBody(token);
        //5. 校验通过放行, 校验失败 返回401
        int result = AppJwtUtil.verifyToken(claims);
        //校验通过, 放行
        if (result == 0 || result == -1) {
            //5.1 获取token中的用户ID
            String userId = claims.get("id").toString();
            //5.2 将userId携带到微服务(放入到请求中)
            ServerHttpRequest httpRequest = request.mutate().headers(httpHeaders -> httpHeaders.add("userId", userId)).build();
            ServerWebExchange webExchange = exchange.mutate().request(httpRequest).build();

            return chain.filter(webExchange);
        }

        //校验失败, 返回401
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        return response.setComplete();
    }
}
